import { LoaderCircle } from "lucide-react";
import { Link, Outlet, useLocation, useNavigation } from "react-router";
import reactIconUrl from "@/assets/react.svg";
import Avatar from "@/components/Avatar";
import Button from "@/components/Button";
import Pending from "@/components/Pending";
import useAuthStore from "@/store/auth";

export default function RootLayout() {
  const loc = useLocation();
  const auth = useAuthStore((state) => state);

  const navigation = useNavigation();
  const isNavigating = Boolean(navigation.location);

  return (
    <div
      className="min-h-screen grid grid-rows-[auto_1fr_auto]"
      style={{ background: "linear-gradient(45deg, #EEEDF5, #f9f8ff)" }}
    >
      <nav className="navbar shadow-sm bg-base-100 sticky top-0 z-10 h-12">
        <div className="flex-none flex gap-4 mx-4">
          <img className="w-6" src="/vite.svg" alt="vite icon" />
          <img className="w-6" src={reactIconUrl} alt="react icon" />
        </div>
        <div className="flex-1 flex gap-4">
          <Link to="/">Home</Link>
          <Link to="/demo">Demo</Link>
        </div>
        <div className="flex-none flex mx-4 items-center gap-4">
          {auth.status === "failed" && <Link to="/login">Login</Link>}
          {auth.status === "loading" && <LoaderCircle className="animate-spin" />}
          {auth.status === "ok" && (
            <>
              <div className="inline-flex items-center gap-4">
                <Avatar src={auth.avatar} alt="my avatar" /> {auth.username}
              </div>
              <Button size="sm" variant="outline" onClick={() => auth.logout()}>
                Logout
              </Button>
            </>
          )}
        </div>
      </nav>
      <main>
        {isNavigating && <Pending />}
        <Outlet />
      </main>
      <footer className="bg-purple-50 border-t border-gray-300 px-4 py-2">
        <p>Footer</p>
        <p>
          <strong>Current route path:</strong> {loc.pathname}
        </p>
      </footer>
    </div>
  );
}
